package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.attr.data.CustAttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author zhoujiao
 * @create 2021-12-12-09:41
 */
public class PersGoSmartContractQuantityAttrHandler extends AbstractAttrHandler<KiteInst, CustAttrData> {
    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, CustAttrData data) {
        super.before(attr, inst, value, data);

        //合同约定开卡总量和订购数量的规则校验
        //模版还原时，不做校验
        if ("sceneTempl".equals(data.getExtAttributes().get("entry"))) {
            return;
        }
        //变更业务的场景初始化过程中不校验
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(data.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
            return;
        }
        String sceneInstId = data.getSceneInstId();
        List<KiteProdInst> kiteProdInstList = querySceneInstService.listProdInsts(sceneInstId);
        int orderNum =0;
        for (KiteProdInst kiteProdInst: kiteProdInstList) {
            if("63249664".equals(kiteProdInst.getSpecId())){//获取框架主产品的订购数量
                KiteAttr kiteAttr = kiteProdInst.getAttr("200001696");
                if (orderNum == 0 && !KiteObjectUtils.isEmpty(kiteAttr) && KiteStringUtils.isNotEmpty(kiteAttr.getValue())) {
                    orderNum = Integer.parseInt(kiteAttr.getValue());
                }
                break;
            }
        }
        if (KiteStringUtils.isEqual("200003677", attr.getFieldName())) { //合同约定开卡总量
            if (KiteStringUtils.isEmpty(value)) {
                return;
            }
            int contractNum = Integer.parseInt(value);
            if (contractNum < orderNum) {
                BssException.throwOut("'订购数量'不允许大于'合同约定订购数量'", "'订购数量'不允许大于'合同约定订购数量'", "'订购数量'不允许大于'合同约定订购数量'");
            }
        }
    }
}

